<template>
  <div class="page-maneger-list">
    <div class="header">
      <el-button @click="handleAddBefore">添加管理员</el-button>

      <el-button @click="fetchData">
        <el-icon><Refresh /></el-icon>
      </el-button>
    </div>
    <el-table :data="dispalyTableData">
      <el-table-column
        prop="adminname"
        label="账号"
        width="80"
      ></el-table-column>
      <el-table-column prop="password" label="密码"></el-table-column>
      <el-table-column prop="role" label="管理员" width="80">
        <template #default="scope">
          <el-tag type="success">{{
            scope.row.role === 1 ? "管理员" : "超级管理员"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handleEdit(scope.row)">编辑</el-button>
          <el-button @click="handleDel(scope.row.adminid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="footer">
      <!-- 分页 -->
      <el-pagination
        v-if="tableData.length > 0"
        background
        layout="prev, pager, next"
        :total="tableData.length"
        v-model:current-page="page"
        :page-size="pageSize"
      />
    </div>

    <!-- 抽屉 属性    :before-close="onClose"-->
    <el-drawer v-model="showDrawer">
      <template #default>
        <el-form :model="formData" :rules="formRules" ref="formRef">
          <el-form-item label="账号" prop="adminname">
            <el-input v-model="formData.adminname"  :disabled="handleType==2"/>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="formData.password" :disabled="handleType==2"/>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="formData.role">
              <el-option value="1" label="超级管理员"/>
              <el-option value="2" label="管理员"/>
            </el-select>
          </el-form-item>
          <el-form-item label="权限" prop="checkedKeys">
            <!-- tree的勾选数据，需要通过方法去主动获取，不能v-model双向绑定 -->
            <el-tree 
            :data="treeData" 
            :props="defaultProps" 
            show-checkbox 
            ref="treeRef"
            node-key="name"
            default-expand-all
            />
          </el-form-item>
        </el-form>
      </template>

      <template #footer>
        <el-button @click="handleEditConfirm" v-if="handleType===2">修改</el-button>
        <el-button @click="handleAdd" v-else>添加</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { getManegerList, delManegerData ,addManeger,updateManeger} from "../../api/user.js";
import {routes} from "@/router"
import { getChildrenByName, isIncludes } from "@/utlis";
export default {
  name: "maneger-list",
  data() {
    return {
      tableData: [],
      page: 1,
      pageSize: 5,
      showDrawer: false, //是否显示抽屉
      formData: {
        adminname: "",
        password: "",
        role: "",
        //勾选的路由的名字
        checkedKeys: [],
      },
      //表单校验
      formRules:{
        adminname:[{required:true,message:"请填写"}],
        password:[{required:true,message:"请填写"}],
        role:[{required:true,message:"请填写"}],
        checkedKeys:[{required:true,message:"请填写"}],
      },
      //抽屉操作类型，添加还是修改 1-添加，2-修改
      handleType:1,
      //树形控件的数据
      treeData: [],
      defaultProps: {
        //每一个节点的子节点是什么字段，默认值就是children
        children: "children",
        //label就是每一个节点用来展示文案的字段,默认值就是label
        label: "label",
      },
    };
  },
  methods: {
    fetchData() {
      getManegerList().then((data) => {
        console.log(data.data);
        this.tableData = data.data;
      });
    },
    handleDel(id) {
      console.log(id);
      delManegerData(id).then((response) => {
        this.fetchData();
        //console.log(response);
      });
    },
    // 抽屉关闭的回调函数
    //done也是一个回调函数，调用才会关闭抽屉
    /* onClose(done){
        console.log(done);
        const isOK=window.confirm("你确定要关闭吗?")
        if(isOK){
            done()
        }
    } */

    //编辑按钮
    handleEdit(row){
        this.showDrawer=true
        this.handleType=2
        //表格数据填充
        this.formData.adminname=row.adminname
        this.formData.password=row.password
        this.formData.role=row.role+''
        
        //checkedKeys不能双向数据绑定，需要别的方法手动勾选
        //等待这次数据更新完成且真实dom渲染完成之后，帮我们调用这个回调函数
        this.$nextTick(()=>{
          //let roles=[...row.checkedKeys]
          let roles = row.checkedKeys;
          let arr=roles.filter((role)=>{
            let children=getChildrenByName(routes,role)
            if(children.length){
              return isIncludes(children,roles)
            }else{
              return true
            }
          })
            this.$refs.treeRef.setCheckedKeys(arr)
        })
        this.formData.checkedKeys=row.checkedKeys
    },
    async handleEditConfirm(){
        try {
            const list1=this.$refs.treeRef.getCheckedKeys()
            const list2=this.$refs.treeRef.getHalfCheckedKeys()
            this.formData.checkedKeys=[...list1,...list2]
            await this.$refs.formRef.validate()

            updateManeger(this.formData).then((data)=>{
                console.log("修改成功");
                this.fetchData();
                this.showDrawer=false
            })
        } catch (error) {
            console.log(error);
        }
    },
    handleAddBefore(){
        this.showDrawer=true
        this.handleType=1
        //重置表单数据
        this.formData.adminname=""
        this.formData.password=""
        this.formData.role=''
        this.formData.checkedKeys=[]
        this.$nextTick(()=>{
            this.$refs.treeRef.setCheckedKeys([])
        })
    },
    async handleAdd() {
        try {
            //校验前需要先获取到节点的keys,赋值给formData.checkedKeys

            //console.log(this.formData);
      //该数据不是想要的不能获取到多个子节点只选中一个节点时的父节点，父节点需要获取
            const list1=this.$refs.treeRef.getCheckedKeys()
            const list2=this.$refs.treeRef.getHalfCheckedKeys()
            this.formData.checkedKeys=[...list1,...list2]

            await this.$refs.formRef.validate()
            addManeger(this.formData).then((data)=>{
                console.log("添加成功");
                this.fetchData();
                this.showDrawer=false
            })
        } catch (error) {
            console.log(error);
        }
      //
      
      
      
    },
    //对routes的数据做处理，不让显示登录页面
    initTreeData(){
        this.treeData=routes.filter((item)=>{
            return !item.hidden
        })

    }
  },
  computed: {
    dispalyTableData() {
      return this.tableData.slice(
        (this.page - 1) * this.pageSize,
        this.page * this.pageSize
      );
    },
  },
  mounted() {
    this.fetchData();
    this.initTreeData()
  },
};
</script>
<style lang="scss">
.page-maneger-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  .footer,
  .header {
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
  }
}

.el-table {
  flex: 1;
}
</style>
